#include <stdio.h>
#include <fstream>

#include "rawfile_plugin.h"
#include "../data/geometrydata.h"

using namespace PBVP;

void RawFilePlugin::initialize(MainInterface* pMainInterface)
{
	//m_pDataManager = pMainInterface->getDataManager();
}

void RawFilePlugin::unload()
{

}

DataInterface* RawFilePlugin::loadFile(const QString &fname)
{
	// Create a geometry datanode and add to the datamanager
	if (! fname.endsWith(".raw")) return NULL;
	
	int i, nv, nt;
	std::ifstream from (fname.toStdString().c_str());
	if(!from.is_open()) return NULL;
	// read header
    from >> nv;
    from >> nt;
	GeometryData *pGeometry = new GeometryData();
	
	for(i = 0; i < nv; i++) {
		float x, y, z;
		from >> x; 
		from >> y;
		from >> z;
		pGeometry->addVertex(x, y, z);
	}

	for(i = 0; i < nt; i++) {
		int index[3];
		from >> index[0];
		from >> index[1];
		from >> index[2];
		pGeometry->addTriangle(index);
	}	
	from.close();
	
	// compute normals
	pGeometry->calcNormals(true);
	// GeometryDataNode *pGeoNode = new GeometryDataNode(pGeometry);
	// pGeoNode->setName(fname);
	// m_pDataManager->addDataNode(pGeoNode);
#ifdef _DEBUG
	printf("add %s to datamanager\n", fname.toStdString().c_str());
#endif
	return pGeometry;
}

bool RawFilePlugin::saveFile(DataInterface* pData, const QString &fname)
{
	// It must be geometry data
	#ifdef __GNU__
	GeometryData *pGeoData = NULL;
	if(pData->getDataSetType() == GEOMETRY_DATA) pGeoData = (GeometryData *)(pData); 
	#else
	GeometryData *pGeoData = dynamic_cast<GeometryData *>(pData);
	#endif
	if(!pGeoData) {
		fprintf(stderr, "Save failed, not a geometry data\n");
		return false;
	}
	std::ofstream out(fname.toStdString().c_str());
	if(!out.is_open()) return false;
	//write the header
	out << pGeoData->numOfVertices() << " " << pGeoData->numOfTriangles() << std::endl;
	for(unsigned int i = 0; i < pGeoData->numOfVertices(); i++) 
	{
		Vector3 v = pGeoData->getVertex(i);
		out << v.x << " " << v.y << " " << v.z << std::endl;
	}
	for(unsigned int i = 0; i < pGeoData->numOfTriangles(); i++)
	{
		unsigned int idx[3];
		pGeoData->getTriangleIndex(i, idx);
		out << idx[0] << " " << idx[1] << " " << idx[2] << std::endl;
	}
	out.close();
	return true;
}

Q_EXPORT_PLUGIN2(rawfile, RawFilePlugin)
